import base64
import cv2
import numpy as np
import requests

from PIL import Image
from io import BytesIO

def show(image,name="image"):
    print("show %s start"%name)

    h = image.shape[0]
    w = image.shape[1]

    # cv2.namedWindow('window', cv2.WINDOW_AUTOSIZE)
    cv2.imshow("%s,%d,%d"%(name,h,w), image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    print("show %s end"%name)



#读取本地图片文件转字符串类型base64
def readImageToBase64():
    with open("data/cut_image.jpg", "rb") as f:
        image_base64 = base64.b64encode(f.read()) # bytes类型
        image_base64 = image_base64.decode("utf-8")  # str类型

    return image_base64


def pillowReadImageToBase64():
    # 1 PIL.Image 对象转图像字节流
    img = Image.open("data/cut_image.jpg")
    img_buffer = BytesIO()
    img.save(img_buffer, format='jpg')
    img_byte = img_buffer.getvalue() # 获得的图片字节流

    image_base64 = base64.b64encode(img_byte)  # bytes类型
    image_base64 = image_base64.decode("utf-8")  # str类型
    return image_base64

#cv2读取本地图片文件转字符串类型base64
def cv2ReadImageToBase64():
    image = cv2.imread("data/cut_image.jpg")

    success, encoded_image = cv2.imencode(".jpg", image)
    if success:
        encoded_image_byte = encoded_image.tobytes()
        image_base64 = base64.b64encode(encoded_image_byte) # bytes类型
        image_base64 = image_base64.decode("utf-8") # str类型
        return image_base64

def readWebImageByte():
    url = "http://t1-q.mafengwo.net/s18/M00/08/E1/CoUBYGDOC9WAH0xBABU_cWDa-54493.jpg?imageMogr2%2Fthumbnail%2F%21305x183r%2Fgravity%2FCenter%2Fcrop%2F%21305x183%2Fquality%2F100"
    res = requests.get(url)

    if 200==res.status_code:
        return res.content

# 字符串类型图片base64转cv2的图片对象
def imageBase64ToCvImage(image_base64):
    print("imageBase64ToCvImage type(image_base64)-1=",type(image_base64))
    image_base64 = image_base64.encode('utf-8')
    print("imageBase64ToCvImage type(image_base64)-2=", type(image_base64))
    # base64解码
    img_data = base64.b64decode(image_base64)
    # 转换为np数组
    # img_array = np.fromstring(img_data, np.uint8)
    img_array = np.frombuffer(img_data, np.uint8)
    # 转换成opencv可用格式
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)

    show(img)
    exit(0)


# 图片base64转Pillow.Image对象
def imageBase64ToPillowImage(image_base64):

    image_base64 = image_base64.encode('utf-8')
    # base64解码
    img_data = base64.b64decode(image_base64) #图片字节流（等同于res.content）

    image = Image.open(BytesIO(img_data)) #Pillow.Image对象

    image.show() #显示Pillow.Image对象的图片
    exit(0)





if __name__ == '__main__':

    # image_base64 = cv2ReadImageToBase64()
    image_base64 = readImageToBase64()
    # image_base64 = pillowReadImageToBase64()

    # image = imageBase64ToCvImage(image_base64)
    image = imageBase64ToPillowImage(image_base64)









